import './tab_title.css';
import template from './tab_title.tmp';
import add_tab_content from '../tab_content/tab_content';
import { removeContent } from '../tab_content/tab_content';

const tab_title = document.getElementById('tab-title');
tab_title.innerHTML = template;
const ul = tab_title.children[0];




export default (title, name) => {

    const arrLi = ul.children;
    let key = false;
    [...arrLi].forEach(item => {
        if (item.dataset.template != title) {
            item.classList.remove('active');
        } else {
            item.classList.add('active');
            key = true;
        }
    })

    if (!key) {
        const li = document.createElement('li');
        li.innerHTML = name;
        const i = document.createElement('i');
        li.appendChild(i);
        li.classList.add('active');
        li.dataset.template = title;
        ul.appendChild(li);

        li.onclick = li_click;
        i.onclick = close;
    }

}





function close(e) {
    e.stopPropagation();
    let template = '';
    const currentLi = e.target.parentElement;
    if (currentLi.classList.contains('active')) {
        if (currentLi.previousElementSibling) {
            currentLi.previousElementSibling.classList.add('active');
            template = currentLi.previousElementSibling.dataset.template;
        } else {
            if (currentLi.nextElementSibling) {
                currentLi.nextElementSibling.classList.add('active');
                template = currentLi.nextElementSibling.dataset.template;
            }
        }
        add_tab_content(template);
    }
    removeContent(currentLi.dataset.template)
    currentLi.remove();

}

function li_click(e) {
    [...ul.children].forEach(item => {
        if (item.dataset.template != e.currentTarget.dataset.template) {
            item.classList.remove('active')
        } else {
            item.classList.add('active');
            add_tab_content(e.currentTarget.dataset.template)
        }
    })
}